﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.Xml;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Renci.SshNet;
using Renci.SshNet.Sftp;

namespace StudyStationWEBAPI.Model
{
    public class SFTP
    {
        private SftpClient sftp;//实例化SftpClient对象
        public bool isConnected //返回服务器的连接状态
		{
            get { return sftp.IsConnected; }
        }
        public SFTP(string host, int port, string username, string password)
        { 
            this.sftp = new SftpClient(host, port, username, password);
        }
		//查看服务器上指定目录的文件列表
		public List<StudyResource> GetFileList(string remotePath)
		{
			List<StudyResource> result = new List<StudyResource>();
			
			this.sftp.Connect();//连接服务器
			IEnumerable<SftpFile> enumerable = this.sftp.ListDirectory(remotePath, null);
			this.sftp.Disconnect();//断开与服务器的连接
			//遍历获取文件的列表
			foreach (SftpFile current in enumerable)
			{
				string name = current.Name;
				if(name!=".."&&name!=".")
                {
					//result.Add(new StudyResource { fileName=name,fileSize=current.Length});
					var newResoure = StudyResourceFactory.getStudyResource("StudyResource");
					newResoure.fileName = name;
					newResoure.fileSize = current.Length;
					result.Add(newResoure);
				}
			}	
			return result;
		}
		//上传文件到服务器
		public bool Put(string localPath, string remotePath)
		{
			try
			{
				using (FileStream fileStream = File.OpenRead(localPath))
				{
					this.sftp.Connect();
					this.sftp.UploadFile(fileStream, remotePath, null);
					this.sftp.Disconnect();
					return true;
				}
			}
			catch(Exception e)
			{
				Console.WriteLine($"上传文件失败{e.Message}");
				return false;
			}
		}
		//下载文件到本地
		public bool Get(string remotePath, string localPath)
		{
			try
			{
				this.sftp.Connect();
				byte[] bytes = this.sftp.ReadAllBytes(remotePath);
				this.sftp.Disconnect();
				File.WriteAllBytes(localPath, bytes);
				return true;
			}
			catch(Exception e)
			{
				Console.WriteLine($"获取文件失败:{e.Message}");
				return false;
			}
		}
	}
}
